<?php
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
	die('Sorry you need php 5 version or greater. Your versoin: ' . PHP_VERSION . '.');
}

class Install {

	private $_currentPath;

	public function  __construct() {
		$this->_currentPath = realpath('.');
	}

	public function Welcome() {
		echo Template::loadTemplate($this->_currentPath . '/template/welcome.html');
	}

	public function Step1() {
		$template = Template::loadTemplate($this->_currentPath . '/template/step1.html');

		$v = explode('.', phpversion());
		$version = (version_compare(PHP_VERSION, '5.0.0', '>')?Template::YES:Template::NO);

		$magic_quotes = Template::magicQuotes();

		$extensions = array('zlib', 'curl', 'session', 'mysqli', 'gd', 'json');
		$extension = Template::Extentions($extensions);

		$directories = array(
			'/public/'              => '0777',
			'/public/downloads/'    => '0777',
			'/public/galleries/'    => '0777',
			'/public/images/'       => '0777',
			'/public/previews/'     => '0777',
			'/public/themes/'       => '0777',
			'/public/tmp/'          => '0777',
			'/public/tmp/cache/'    => '0777',
			'/public/system/tmp/'   => '0777'
		);
		//$directory = Template::PermissionForDirectories($directories);
		$directory = Template::writeInFolders($directories);

		$files = array(
			'/public/.htaccess'                             => '0666',
			'/public/robots.txt'                            => '0666',
			'/public/sitemap.xml'                           => '0666',
			'/application/configs/routesext.xml'            => '0666',
			'/public/system/js/tiny_mce/link_list.js'       => '0666',
			'/application/configs/application.ini'          => '0666',
			'/public/tmp/pfs.prs'                           => '0666'
		);
		//$file = Template::PermissionForFiles($files);
		$file = Template::writeInFiles($files);
		$navigation = Template::Navigation(1);

		$template = str_replace('{$version}', $version, $template);
		$template = str_replace('{$magic_quotes}', $magic_quotes, $template);
		$template = str_replace('{$extensions}', $extension, $template);
		$template = str_replace('{$directories}', $directory, $template);
		$template = str_replace('{$files}', $file, $template);
		$template = str_replace('{$navigation}', $navigation, $template);
		echo $template;
	}

	public function Step2() {
		$template = Template::loadTemplate($this->_currentPath . '/template/step2.html');
		$message = $class = $db = $user = $password = $success = '';
		$host = 'localhost';

		if(!empty($_POST) && isset($_POST['create']) && $_POST['create'] == 'Create') {
			$flag = Functions::connectByDatabase($_POST['host'], $_POST['db'], $_POST['user'], $_POST['password']);

			if($flag == 'true') {
				$class = 'success';
				$message = 'The database was created.';
				$success = '<div id="success"></div>';
			} else {
				$class = 'errors';
				$message = $flag;
				Template::setError('Wrong data');
			}
			$host = (isset($_POST['host'])?trim($_POST['host']):'');
			$db = (isset($_POST['db'])?trim($_POST['db']):'');
			$user = (isset($_POST['user'])?trim($_POST['user']):'');
			$password = (isset($_POST['password'])?trim($_POST['password']):'');
		} else {
			Template::setError('Need enter data');
		}

		$navigation = Template::Navigation(2);

		$template = str_replace('{$success}', $success, $template);
		$template = str_replace('{$host}', $host, $template);
		$template = str_replace('{$user}', $user, $template);
		$template = str_replace('{$password}', $password, $template);
		$template = str_replace('{$db}', $db, $template);
		$template = str_replace('{$navigation}', $navigation, $template);
		$template = str_replace('{$class}', $class, $template);
		$template = str_replace('{$message}', $message, $template);
		echo $template;
	}

	public function Step3() {
		$template = Template::loadTemplate($this->_currentPath . '/template/step3.html');
		$site_url = $admin_email = $use_smtp = $smtp_host = $smtp_login = $smtp_password =
			$login = $password = $success =  '';
		$img_small = 200; $img_medium = 300; $img_large = 400; $img_max_width = 1024;
		$video_width = 320; $video_height = 240;

		if(!empty($_POST) && isset($_POST['done']) && $_POST['done'] == 'Done') {
			Functions::saveConfiguration($_POST);
			$site_url = (isset($_POST['site_url'])?$_POST['site_url']:'');
			$admin_email = (isset($_POST['admin_email'])?$_POST['admin_email']:'');
			$img_small = (isset($_POST['img_small'])?$_POST['img_small']:'');
			$img_medium = (isset($_POST['img_medium'])?$_POST['img_medium']:'');
			$img_large = (isset($_POST['img_large'])?$_POST['img_large']:'');
			$use_smtp = (isset($_POST['use_smtp']) && $_POST['use_smtp']=='on'?'checked="checked"':'');
			$smtp_host = (isset($_POST['smtp_host'])?$_POST['smtp_host']:'');
			$smtp_login =  (isset($_POST['smtp_login'])?$_POST['smtp_login']:'');
			$smtp_password = (isset($_POST['smtp_password'])?$_POST['smtp_password']:'');
			$img_max_width = (isset($_POST['img_max_width'])?$_POST['img_max_width']:'');
			$video_width = (isset($_POST['video_width'])?$_POST['video_width']:'');
			$video_height = (isset($_POST['video_height'])?$_POST['video_height']:'');
			$login = (isset($_POST['login'])?$_POST['login']:'');
			$password = (isset($_POST['password'])?$_POST['password']:'');
			$success = '<div id="success"></div>';
		} else {
			Template::setError('Need enter data');
		}
		$navigation = Template::Navigation(3);

		$template = str_replace('{$success}', $success, $template);
		$template = str_replace('{$site_url}', $site_url, $template);
		$template = str_replace('{$admin_email}', $admin_email, $template);
		$template = str_replace('{$img_small}', $img_small, $template);
		$template = str_replace('{$img_medium}', $img_medium, $template);
		$template = str_replace('{$img_large}', $img_large, $template);
		$template = str_replace('{$use_smtp}', $use_smtp, $template);
		$template = str_replace('{$smtp_host}', $smtp_host, $template);
		$template = str_replace('{$smtp_login}', $smtp_login, $template);
		$template = str_replace('{$smtp_password}', $smtp_password, $template);
		$template = str_replace('{$img_max_width}', $img_max_width, $template);
		$template = str_replace('{$video_width}', $video_width, $template);
		$template = str_replace('{$video_height}', $video_height, $template);
		$template = str_replace('{$login}', $login, $template);
		$template = str_replace('{$password}', $password, $template);
		$template = str_replace('{$navigation}', $navigation, $template);
		echo $template;
	}

	public function ThankYou() {
		$template = Template::loadTemplate($this->_currentPath . '/template/thankyou.html');
		$config = parse_ini_file(realpath('../../') . '/application/configs/application.ini', true);
		$website_url = $config['website']['website.url'];
		$template = str_replace('{$site_url}', $website_url, $template);
		echo $template;
	}
}

class Functions {

	static public function changePermission($path, $mode) {
		@chmod($path, $mode);
		$perm = substr(sprintf('%o', fileperms($path)), -4);
		if($perm == $mode) {
			return true;
		}
		return false;
	}

	static public function connectByDatabase($host, $db, $user, $password) {
		$link = @mysql_connect($host, $user, $password);
		if($link === false) {
			return mysql_error();
		}

		if(!mysql_select_db($db, $link)) {
			return mysql_error();
		}

		$queries = Queries::$queries;
		foreach($queries as $query) {
			self::runQuery($query);
		}
		@mysql_close($link);

		$fileName = realpath('.') . '/config.txt';
		if(file_exists($fileName)) {
			$content = file_get_contents($fileName);
			if($content === false) {
				throw new Exception("Can't read file (" . $fileName . ").");
			}
			$content = str_replace('{$host}', $host, $content);
			$content = str_replace('{$user}', $user, $content);
			$content = str_replace('{$password}', $password, $content);
			$content = str_replace('{$db}', $db, $content);
			$content = str_replace('{$path}', realpath('../../') . '/', $content);
			if(false === file_put_contents(realpath('../../') . '/application/configs/application.ini', $content)) {
				throw new Exception("Can't save file (" . realpath('../../') . "/application/configs/application.ini).");
			}
		} else {
			throw new Exception("Can't find file $fileName or this file doesn't exist");
		}

		return 'true';
	}

	static public function saveConfiguration($data) {
		if(file_exists(realpath('../../') . '/application/configs/application.ini')) {
			$config = parse_ini_file(realpath('../../') . '/application/configs/application.ini', true);
			$host = $config["database : production"]["database.params.host"];
			$user = $config["database : production"]["database.params.username"];
			$password = $config["database : production"]["database.params.password"];
			$db = $config["database : production"]["database.params.dbname"];

			$link = @mysql_connect($host, $user, $password);
			if($link === false) {
				throw new Exception(mysql_error());
			}
			if(!mysql_select_db($db, $link)) {
				throw new Exception(mysql_error());
			}

			if(isset($data['admin_email']) && preg_match("/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})$/", trim($data['admin_email']))) {
				self::runQuery("update config set value = '" . trim($data['admin_email']) . "'  where name = 'admin_email'");
			}
			if(isset($data['img_small']) && intval($data['img_small']) > 0) {
				self::runQuery("update config set value = " . intval($data['img_small']) . "  where name = 'img_small'");
			}
			if(isset($data['img_medium']) && intval($data['img_medium']) > 0) {
				self::runQuery("update config set value = " . intval($data['img_medium']) . " where name = 'img_medium'");
			}
			if(isset($data['img_large']) && intval($data['img_large']) > 0) {
				self::runQuery("update config set value = " . intval($data['img_large']) . "  where name = 'img_large'");
			}
			if(isset($data['use_smtp']) && $data['use_smtp'] == 'on') {
				self::runQuery("update config set value = '" . (isset($data['smtp_host'])?trim($data['smtp_host']):'') . "'  where name = 'smtp_host'");
				self::runQuery("update config set value = '" . (isset($data['smtp_password'])?trim($data['smtp_password']):'') . "'  where name = 'smtp_password'");
				self::runQuery("update config set value = '" . (isset($data['smtp_login'])?trim($data['smtp_login']):'') . "'  where name = 'smtp_login'");
				self::runQuery("update config set value = " . ($data['use_smtp']=='on'?"1":"0") . "  where name = 'use_smtp'");
			}
			if(isset($data['img_max_width']) && intval($data['img_max_width']) > 0) {
				self::runQuery("update config set value = " . intval($data['img_max_width']) . "  where name = 'img_max_width'");
			}
			if(isset($data['video_width']) && intval($data['video_width']) > 0) {
				self::runQuery("update config set value = " . intval($data['video_width']) . "  where name = 'video_width'");
			}
			if(isset($data['video_height']) && intval($data['video_height']) > 0) {
				self::runQuery("update config set value = " . intval($data['video_height']) . "  where name = 'video_height'");
			}
			if(isset($data['login']) && trim($data['login']) != '' && isset($data['password']) && trim($data['password']) != '') {
				self::runQuery("insert into `user`(`role_id`,`id_user_seosamba`,`login`,`password`,`email`,`status`,`nickname`,`last_login`,`ipaddress`,`reg_date`) values (3,0,'" . $data['login'] . "',md5('" . $data['password'] . "'),'" . $data['admin_email'] . "','active','admin',NULL,NULL, NOW())");
			}
			@mysql_close($link);

			if(isset($data['site_url']) && preg_match("/^(http|https):\/\/(.+)$/", $data['site_url'])) {
				$siteURL = $data['site_url'] . ($data['site_url'][strlen($data['site_url'])-1] != '/'?'/':'');
				$content = file_get_contents(realpath('../../') . '/application/configs/application.ini');
				if($content === false) {
					throw new Exception("Can't read file (" . realpath('../../') . "/application/configs/application.ini).");
				}
				$content = str_replace('{$site_url}', $siteURL, $content);
				if(false === file_put_contents(realpath('../../') . '/application/configs/application.ini', $content)) {
					throw new Exception("Can't save file (" . realpath('../../') . "/application/configs/application.ini).");
				}
				self::saveHtaccessFile($siteURL);
				self::saveRoutes($siteURL);
			} else {
				throw new Exception("Can't find  website URL.");
			}
		} else {
			throw new Exception("Can't find file (" . realpath('../../') . "/application/configs/application.ini) or this file doesn't exist.");
		}
	}

	static public function runQuery($query) {
		$success = @mysql_query($query);
		if($success === false) {
			throw new Exception(mysql_error());
		}
	}

	static public function saveHtaccessFile($siteURL) {
		if(file_exists(realpath('.') . '/htaccess.txt')) {
			$content = file_get_contents(realpath('.') . '/htaccess.txt');
			if($content === false) {
				throw new Exception("Can't read file (" . realpath('.') . "/htaccess.txt).");
			}
			$content = str_replace('{$site_url}', $siteURL, $content);
			if(false === file_put_contents(realpath('../') . '/.htaccess', $content)) {
				throw new Exception("Can't save file (" . realpath('../') . "/.htaccess).");
			}
		} else {
			throw new Exception("Can't find file (" . realpath('.') . "/htaccess.txt) or this file doesn't exist.");
		}
	}

	static public function saveRoutes($siteURL) {
		if(file_exists(realpath('../') . '/system/misc/routest.tpl.phtml')) {
			$content = file_get_contents(realpath('../') . '/system/misc/routest.tpl.phtml');
			if($content === false) {
				throw new Exception("Can't read file (" . realpath('../') . "/system/misc/routest.tpl.phtml).");
			}
			$url = '';
			$parseURL = parse_url($siteURL);
			if(isset($parseURL['path'])) {
				$tmpUrl = trim($parseURL['path'], '/');
				if($tmpUrl != '') {
					$url = $tmpUrl;
				}
			}
			$content = str_replace('%sitedir%', $url, $content);
			if(false === file_put_contents(realpath('../../') . '/application/configs/routesext.xml', $content)) {
				throw new Exception("Can't save file (" . realpath('../../') . "/application/configs/routesext.xml).");
			}
		} else {
			throw new Exception("Can't find file (" . realpath('../') . "/system/misc/routest.tpl.phtml) or this file doesn't exist.");
		}
	}
}

class Template {

	const YES = '<span style="color:green;">Yes</span>';
	const NO = '<span style="color:red;">No</span>';


	static public $errors = array();

	static function loadTemplate($path) {
		$content = file_get_contents($path);
		if($content === false) {
			throw new Exception("Can't read file (" . $path . ").");
		}
		return $content;
	}

	static public function Extentions($allow) {
		$extensions = get_loaded_extensions();
		$content = '';
		foreach($allow as $extension) {
			$content .= "<tr>\n<td align=\"left\"><label>" . $extension . ":</label></td>\n";
			$content .= "<td align=\"right\">";
			if(in_array($extension, $extensions)) {
				$content .= self::YES;
			} else {
				$content .= self::NO;
				self::setError("Your need extension: $extension");
			}
			$content .= "</td>\n</tr>\n";
		}
		return $content;
	}


	static public function writeInFolders($allow) {
	$content = '';
		$root = realpath('../../');
		foreach ($allow as $key => $value) {
			$content .= "<tr>\n<td align=\"left\"><label>" . $key . "</label></td>\n";
			$content .= "<td align=\"right\">";
			if(is_dir($root . $key)) {
					if(is_writable($root . $key))
				{
					$content .= self::YES;
				}else
				{
					$content .= self::NO;//"<span style=\"color:red;font-size:14px;font-weight:bold;\">You need to make folder $key writable.</span>";
					self::setError("Folder $key  must be writable");
				}
			
			} else {
				$content .= '<span style="color:red;">You need create this folder</span>';
				self::setError("You need create $key folder and make it writable");
			}
			$content .= "</td>\n</tr>\n";
		}
		return $content;
	}

	static public function writeInFiles($allow) {
		//forprsculpting
		$contentToWrite = '#Test';
		$content = '';
		$root = realpath('../../');
		$res=null;
		foreach ($allow as $key => $value) {
			$content .= "<tr>\n<td align=\"left\"><label>" . $key . "</label></td>\n";
			$content .= "<td align=\"right\">";
			if(file_exists($root . $key)) {
				
				if(is_writable($root . $key))
				{
					$content .= self::YES;
				}else
				{
					$content .= self::NO; //$content .= "<span style=\"color:red;font-size:14px;font-weight:bold;\">You need to make file $key writable.</span>";
					self::setError("File $key  must be writable");
				}

			} else {
				$content .= '<span style="color:red;">You need create this file</span>';
				self::setError("You need create $key file and make it writable");
			}
			$content .= "</td>\n</tr>\n";
		}
		return $content;

	}

	static public function PermissionForDirectories($allow) {
		$content = '';
		$root = realpath('../../');
		foreach ($allow as $key => $value) {
			$content .= "<tr>\n<td align=\"left\"><label>" . $key . "</label></td>\n";
			$content .= "<td align=\"right\">";
			if(is_dir($root . $key)) {
				$perm = substr(sprintf('%o', fileperms($root . $key)), -4);
				if($perm == $value) {
					$content .= self::YES;
				} else {
                    /*if(Functions::changePermission($root . $key, $value)) {
                        $content .= self::YES;
                    } else {
                        $content .= "<span style=\"color:red;font-size:14px;font-weight:bold;\">You need chmod $value</span>";
                        self::setError("Need change permission for directory $key  chmod $value");
                    }*/
					$content .= "<span style=\"color:red;font-size:14px;font-weight:bold;\">You need chmod $value</span>";
					self::setError("Need change permission for directory $key  chmod $value");
				}
			} else {
				$content .= '<span style="color:red;">You need create this folder</span>';
				self::setError("You need create $key folder and set chmod $value");
			}
			$content .= "</td>\n</tr>\n";
		}
		return $content;
	}

	static public function PermissionForFiles($allow) {
		$content = '';
		$root = realpath('../../');
		foreach ($allow as $key => $value) {
			$content .= "<tr>\n<td align=\"left\"><label>" . $key . "</label></td>\n";
			$content .= "<td align=\"right\">";
			if(file_exists($root . $key)) {
				$perm = substr(sprintf('%o', fileperms($root . $key)), -4);
				if($perm == $value) {
					$content .= self::YES;
				} else {
                        /*if(Functions::changePermission($root . $key, $value)) {
                            $content .= self::YES;
                        } else {
                            $content .= "<span style=\"color:red;font-size:14px;font-weight:bold;\">You need chmod $value</span>";
                            self::setError("Need change permission for file $key  chmod $value");
                        }*/
					$content .= "<span style=\"color:red;font-size:14px;font-weight:bold;\">You need chmod $value</span>";
					self::setError("Need change permission for file $key  chmod $value");
				}
			} else {
				$content .= '<span style="color:red;">You need create this file</span>';
				self::setError("You need create $key file and set chmod $value");
			}
			$content .= "</td>\n</tr>\n";
		}
		return $content;
	}

	static public function magicQuotes() {
		$content = '';
		$content .= "<tr>\n<td align=\"left\"><label>magic_quotes_gpc</label></td>\n";
		$content .= "<td align=\"right\">" . (get_magic_quotes_gpc() == 0?'<span style="color:green;">Off</span>':'<span style="margin-right:10px;">turn it Off (recomended)</span><span style="color:red;">On</span>') . "</td></tr>";
		$content .= "<tr>\n<td align=\"left\"><label>magic_quotes_runtime</label></td>\n";
		$content .= "<td align=\"right\">" . (get_magic_quotes_runtime() == 0?'<span style="color:green;">Off</span>':'<span style="margin-right:10px;">turn it Off (recomended)</span><span style="color:red;">On</span>') . "</td></tr>";
		return $content;
	}

	static public function setError($error) {
		self::$errors[] = $error;
	}

	static public function getErrors() {
		return self::$errors;
	}

	static public function Navigation($step) {
		$content = "<div class=\"navigation\">\n";
		$content .= "<div class=\"back\">\n";
		$content .= "<form action=\"index.php\" method=\"post\">\n";
		$content .= "<input type=\"hidden\" name=\"step\" value=\"" . ($step-1) . "\">\n";
		$content .= "<input type=\"submit\" name=\"back\" value=\"Back\">\n</form>\n</div>\n";
		$content .= "<div class=\"next\">\n";
		$errors = self::$errors;
		if(empty($errors)) {
			$content .= "<form action=\"index.php\" method=\"post\">\n";
			$content .= "<input type=\"hidden\" name=\"step\" value=\"" . ($step+1) . "\">\n";
			$content .= "<input type=\"submit\" name=\"next\" value=\"Next\">\n</form>\n";
		} else {
			if($step == 1 ) {
				$content .= "<form action=\"index.php\" method=\"post\">\n";
				$content .= "<input type=\"hidden\" name=\"step\" value=\"" . $step . "\">\n";
				$content .= "<input type=\"submit\" name=\"check\" value=\"Check Again\">\n</form>\n";
			}
		}
		$content .= "</div></div>\n";
		return $content;
	}

}

class Queries {

	static public $queries = array(
	"CREATE TABLE `category` (
  		`id` int(10) NOT NULL auto_increment,
  		`id_parent` int(11) default NULL,
  		`name` varchar(64) default NULL,
	PRIMARY KEY  (`id`),
	KEY `parentId` (`id_parent`)
	) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=utf8;" 
	,
	"CREATE TABLE `comment` (
  		`id` int(10) unsigned NOT NULL auto_increment,
  		`content` text,
  		`container_id` int(10) unsigned NOT NULL,
  		`date` datetime default NULL,
  		`user_id` int(10) unsigned NOT NULL,
  		`user_email` varchar(60) default '',
  		`abuse` tinyint(1) default '0',
  		`user_sign` varchar(40) default '',
  		`user_website` varchar(40) default '',
  		`publish` tinyint(1) default '1',
  		`rank` tinyint(3) default '0',
  		`topic` varchar(60) default '',
  		`keyword` varchar(60) default '',
  		`notify` tinyint(1) default '0',
  	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=92 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `config` (
  		`name` varchar(100) NOT NULL default '',
  		`value` varchar(255) NOT NULL,
  	PRIMARY KEY  (`name`)
	) ENGINE=MyISAM DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `container` (
  		`id` int(10) unsigned NOT NULL auto_increment,
  		`container_type_id` int(10) unsigned NOT NULL,
  		`user_id` int(11) NOT NULL,
  		`page_id` int(11) NOT NULL,
  		`name` varchar(255) default NULL,
  		`options_values` varchar(255) default NULL,
  		`published` enum('0','1') default '1',
  		`is_forsale` enum('0','1') default '0',
		`price` float default NULL,
		`first_option` varchar(255) default NULL,
		`second_option` varchar(255) default NULL,
		`allow_comments` enum('0','1') default '1',
		`publishing_date` datetime default NULL,
  	PRIMARY KEY  (`id`)
	) ENGINE=MyISAM AUTO_INCREMENT=59 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `container_type` (
  		`id` int(10) unsigned NOT NULL auto_increment,
  		`name` varchar(255) default NULL,
  		`template` varchar(255) default NULL,
  	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `content` (
  		`id` int(10) unsigned NOT NULL auto_increment,
  		`id_language` int(10) unsigned NOT NULL,
  		`id_container` int(10) unsigned NOT NULL,
  		`value` text,
  	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `deeplink` (
  		`id` int(10) unsigned NOT NULL auto_increment,
  		`name` varchar(255) NOT NULL,
		`url` varchar(255) NOT NULL,
  		`type` enum('int','ext') default 'int',
  		`ban` enum('0','1') NOT NULL default '0',
  		`nofollow` enum('0','1') NOT NULL default '0',
  		`ext_ws_id` int(10) unsigned default NULL,
  	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `deeplink_content` (
  		`deeplink_id` int(11) unsigned NOT NULL,
  		`content_id` int(11) unsigned NOT NULL
	) ENGINE=MyISAM DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `featured_area` (
  		`id` int(10) unsigned NOT NULL auto_increment,
  		`name` varchar(164) NOT NULL,
  		`content` text,
  		`order` tinyint(3) default NULL,
  	PRIMARY KEY  (`id`)
	) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `forms` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`name` varchar(64) NOT NULL,
		`code` text NOT NULL,
		`email` varchar(64) NOT NULL,
		`successMessage` text NOT NULL,
		`errorMessage` text NOT NULL,
		`emailFrom` varchar(64) NOT NULL,
		`emailMessage` text NOT NULL,
		`useSMTP` enum('0','1') NOT NULL default '0',
	PRIMARY KEY  (`id`)
	) ENGINE=MyISAM DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `language` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`name` varchar(64) default NULL,
  	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `link_reference` (
		`id_container` int(10) unsigned default NULL,
		`link` varchar(255) default NULL
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `message` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`user_id` int(10) unsigned NOT NULL,
		`content` text,
		`date_sent` datetime default NULL,
	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `news` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`id_newscategory` int(10) unsigned NOT NULL,
		`title` varchar(255) NOT NULL,
		`page_url` varchar(255) default NULL,
		`intro` text NOT NULL,
		`text` text NOT NULL,
		`date` datetime NOT NULL,
		`order` int(10) unsigned NOT NULL,
		`is_archived` enum('0','1') NOT NULL default '0',
		`is_featured` enum('0','1') NOT NULL default '0',
		`disable_archive` enum('0','1') NOT NULL default '0',
		`last_update` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  	PRIMARY KEY  (`id`)
	) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `newscategory` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`name` varchar(255) NOT NULL,
	PRIMARY KEY  (`id`)
	) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `page` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`template_id` int(10) unsigned NOT NULL,
		`category_id` int(11) NOT NULL,
		`nav_name` varchar(255) default NULL,
		`meta_description` text,
		`meta_keywords` text,
		`header_title` varchar(255) default NULL,
		`h1` varchar(255) default NULL,
		`url` varchar(255) default NULL,
		`short_description` text,
		`date` datetime default NULL,
		`owner` int(10) unsigned default NULL,
		`last_update` datetime default NULL,
		`is_404page` enum('0','1') default '0',
		`bestpractices` enum('1','0') default '0',
		`show_in_menu` enum('0','1','2','3') default '0',
		`order` tinyint(3) unsigned default NULL,
		`static_order` tinyint(4) default NULL,
		`weight` tinyint(3) unsigned default '0',
		`seosamba_rule_id` int(10) unsigned default NULL,
		`silo_id` int(10) unsigned default NULL,
	PRIMARY KEY  (`id`)
	) ENGINE=MyISAM AUTO_INCREMENT=83 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `page_changelog` (
		`page_id` int(10) unsigned NOT NULL,
		`header_title` varchar(255) default NULL,
		`url` varchar(255) default NULL,
		`meta_keywords` text,
		`meta_description` text
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `page_has_fa` (
		`page_id` int(10) unsigned NOT NULL,
		`fa_id` int(10) unsigned NOT NULL
	) ENGINE=MyISAM DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `page_image` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`page_id` int(10) unsigned NOT NULL,
		`name` varchar(255) default NULL,
		`path` varchar(255) default NULL,
		`description` text,
	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `plugin` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`name` varchar(255) default NULL,
		`status` enum('enabled','disabled') default 'disabled',
		PRIMARY KEY  (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `renamed_pages` (
		`id_page` int(10) unsigned default NULL,
		`url` varchar(255) default NULL,
		`new_url` varchar(255) default NULL,
		`original_old_url` varchar(255) default ''
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `role` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`name` varchar(45) default NULL,
	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `seo_data` (
		`page_id` int(10) unsigned default NULL,
		`seo_top` longtext,
		`seo_bottom` longtext,
	UNIQUE KEY `page_id` (`page_id`)
	) ENGINE=MyISAM DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `silo` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`name` varchar(65) default NULL,
		`as_cat` enum('0','1') default '0',
	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `template` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`name` varchar(45) default NULL,
		`content` text,
		`preview_path` varchar(60) default NULL,
		`theme_name` varchar(60) default NULL,
	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=192 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `user` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`role_id` int(10) unsigned NOT NULL,
		`id_user_seosamba` int(10) unsigned default NULL,
		`login` varchar(30) default NULL COMMENT 'user login',
		`password` varchar(35) default NULL COMMENT 'user password',
		`email` varchar(45) default NULL,
		`status` enum('active','banned','blocked') default 'active',
		`nickname` varchar(40) default NULL,
		`last_login` datetime default NULL,
		`ipaddress` varchar(30) default NULL,
		`reg_date` datetime default NULL,
	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `user_page_permission` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`id_user` int(10) unsigned default NULL,
		`id_page` int(10) unsigned default NULL,
	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `variable_content` (
		`name` varchar(250) NOT NULL default '',
		`value` text NOT NULL,
	PRIMARY KEY  (`name`)
	) ENGINE=MyISAM DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `website_info` (
		`id` int(10) unsigned NOT NULL auto_increment,
		`name` varchar(45) default NULL,
		`url` varchar(255) default NULL,
		`description` text,
		`address` varchar(255) default NULL,
		`phone` varchar(64) default NULL,
		`fax` varchar(64) default NULL,
		`industry` varchar(128) default NULL,
		`geo_code` int(11) default NULL,
		`email` varchar(255) default NULL,
	PRIMARY KEY  (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
	,
	"CREATE TABLE `whitelabel_services` (
		`cpanel_logo` varchar(255) default NULL,
		`services_content` text
	) ENGINE=MyISAM DEFAULT CHARSET=utf8;"
	,
	"insert into `config`(`name`,`value`) values ('current_theme','default'),('default_page','index'),('zfp',''),('admin_email','admin@localhost'),('img_small','200'),('img_medium','300'),('img_large','450'),('img_page_desc_large',''),('img_page_desc_small',''),('smtp_host',''),('smtp_password',''),('smtp_login',''),('use_smtp','0'),('img_max_width','1024'),('video_width','320'),('video_height','240'),('plugin_cache','0'), ('default_news_folder', 'news');"
	,
	"insert  into `role`(`id`,`name`) values (1,'admin'),(2,'user'),(3,'superadmin');"
	,
	"insert into `page`(`template_id`,`category_id`,`nav_name`,`meta_description`,`meta_keywords`,`header_title`,`h1`,`url`,`short_description`,`date`,`owner`,`last_update`,`is_404page`,`bestpractices`,`show_in_menu`,`order`,`static_order`,`weight`,`seosamba_rule_id`)
		values (3,1,'home','home','home page','home','home','index','',NOW(),1,NULL,'0','0','1',100,100,0,0),
		(1,-1,'no category','','','no category','no category','no-category','',NOW(),1,NULL,'0','0','1',0,100,0,0);"
	,
	"insert  into `category`(`id`,`id_parent`,`name`) values (-1,0,'no category'),(1,-1,'home');"
	,
	"insert  into `template`(`id`,`name`,`content`,`preview_path`,`theme_name`)
		values (1,'category','<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\r\n<head>\r\r\n<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\r\r\n<title>{\$page_title}</title>\r\r\n<meta name=\"keywords\" content=\"{\$meta_keywords}\" /> \r\r\n<meta name=\"description\" content=\"{\$meta_description}\" /> \r\r\n<link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\r\r\n<link href=\"content.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\r\r\n</head>\r\r\n\r\r\n\r\r\n<body>\r\r\n<div id=\"wrapper\">\r\r\n{\$static_menu}\r\r\n<!-- start page -->\r\r\n<div id=\"page\">\r\r\n	<!-- start content -->\r\r\n	<div id=\"content\">\r\r\n	<div id=\"logo\">{\$content:topimage}\r\r\n    <div id=\"logo-title\">\r\r\n   <h1>{\$header:slogan}</h1>\r\r\n    </div>\r\r\n    	</div>\r\r\n		<div class=\"post\">\r\r\n			<h2 class=\"title\">{\$header:3}</h2> \r\r\n			<div class=\"entry\">\r\r\n		{\$content:2}\r\r\n		  </div>\r\r\n<h2 class=\"title\">All {\$page_h1} in {\$category_name}</h2>\r\r\n<div id=\"menuimg\">{\$pages_list_img}</div>\r\r\n		</div>\r\r\n		\r\r\n	</div>\r\r\n	<!-- end content -->\r\r\n	<!-- start sidebars -->\r\r\n	<div id=\"sidebar1\" class=\"sidebar\">\r\r\n		{\$main_menu}\r\r\n	</div>\r\r\n	<div id=\"sidebar2\" class=\"sidebar\">\r\r\n		\r\r\n				<h2>{\$header:2}</h2>\r\r\n\r\r\n{\$content:1}\r\r\n\r\r\n<h2>{\$header:4}</h2>\r\r\n\r\r\n{\$content:3}\r\r\n\r\r\n			\r\r\n	</div>\r\r\n	<!-- end sidebars -->\r\r\n	<div style=\"clear: both;\">&nbsp;</div>\r\r\n<!-- end page -->\r\r\n</div>\r\r\n<div id=\"footer\">\r\r\n	{\$static:footer}\r\r\n</div>\r\r\n</div>\r\r\n</body>\r\r\n</html>','category.jpg','default'),
			(2,'default','<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\r\n<head>\r\r\n<meta name=\"google-site-verification\" content=\"jlPUD5SVPm4gKxr1AvDNT7e1khf8uzP5D15mRvasIpI\" />\r\r\n<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\r\r\n<title>{\$page_title}</title>\r\r\n<meta name=\"keywords\" content=\"{\$meta_keywords}\" /> \r\r\n<meta name=\"description\" content=\"{\$meta_description}\" /> \r\r\n<link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\r\r\n<link href=\"content.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\r\r\n</head>\r\r\n\r\r\n\r\r\n\r\r\n<body>\r\r\n<div id=\"wrapper\">\r\r\n{\$static_menu}\r\r\n<!-- start page -->\r\r\n<div id=\"page\">\r\r\n	<!-- start content -->\r\r\n	<div id=\"content\">\r\r\n\r\r\n	<div id=\"logo\">{\$content:topimage}\r\r\n    <div id=\"logo-title\">\r\r\n   <h1>{\$header:slogan}</h1>\r\r\n    </div>\r\r\n    	</div>\r\r\n		<div class=\"post\">\r\r\n			<h2 class=\"title\">{\$header:3}</h2> \r\r\n			<div class=\"entry\">\r\r\n				{\$content:2}\r\r\n		  </div>\r\r\n\r\r\n		</div>\r\r\n		\r\r\n	</div>\r\r\n	<!-- end content -->\r\r\n	<!-- start sidebars -->\r\r\n	<div id=\"sidebar1\" class=\"sidebar\">\r\r\n	{\$main_menu}	\r\r\n<script language=\"javascript\">setPage();</script>\r\r\n	</div>\r\r\n	<div id=\"sidebar2\" class=\"sidebar\">\r\r\n		\r\r\n				<h2>{\$header:2}</h2>\r\r\n\r\r\n{\$content:1}\r\r\n\r\r\n<h2>{\$header:4}</h2>\r\r\n\r\r\n{\$content:3}\r\r\n\r\r\n\r\r\n\r\r\n			\r\r\n	</div>\r\r\n	<!-- end sidebars -->\r\r\n	<div style=\"clear: both;\">&nbsp;</div>\r\r\n<!-- end page -->\r\r\n</div>\r\r\n<div id=\"footer\">\r\r\n	{\$static:footer}\r\r\n</div>\r\r\n</div>\r\r\n\r\r\n</body>\r\r\n</html>','default.jpg','default'),
            (3,'index','<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\r\n<head>\r\r\n<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\r\r\n<title>{\$page_title}</title>\r\r\n<meta name=\"keywords\" content=\"{\$meta_keywords}\" /> \r\r\n<meta name=\"description\" content=\"{\$meta_description}\" /> \r\r\n<link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\r\r\n<link href=\"content.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\r\r\n</head>\r\r\n\r\r\n<body>\r\r\n<div id=\"wrapper\">\r\r\n{\$static_menu}\r\r\n<!-- start page -->\r\r\n<div id=\"page\">\r\r\n	<!-- start content -->\r\r\n	<div id=\"content\">\r\r\n	<div id=\"logo\">{\$content:topimage}\r\r\n    <div id=\"logo-title\">\r\r\n   <h1>{\$header:slogan}</h1>\r\r\n    </div>\r\r\n    	</div>\r\r\n		<div class=\"post\">\r\r\n			<h2 class=\"title\">{\$header:3}</h2> \r\r\n			<div class=\"entry\">\r\r\n				{\$content:2}\r\r\n\r\r\n		  </div>\r\r\n		</div>\r\r\n		\r\r\n	</div>\r\r\n	<!-- end content -->\r\r\n	<!-- start sidebars -->\r\r\n	<div id=\"sidebar1\" class=\"sidebar\">\r\r\n		{\$main_menu}\r\r\n\r\r\n	</div>\r\r\n	<div id=\"sidebar2\" class=\"sidebar\">\r\r\n		\r\r\n				<h2>{\$header:4}</h2>\r\r\n\r\r\n<div>{\$content:farea1}</div>\r\r\n\r\r\n<h2>{\$header:5}</h2>\r\r\n\r\r\n<div>{\$content:farea2}</div>\r\r\n\r\r\n{\$content:addright1}\r\r\n			\r\r\n	</div>\r\r\n	<!-- end sidebars -->\r\r\n	<div style=\"clear: both;\">&nbsp;</div>\r\r\n<!-- end page -->\r\r\n</div>\r\r\n<div id=\"footer\">\r\r\n	{\$static:footer}\r\r\n</div>\r\r\n</div>\r\r\n</body>\r\r\n</html>','index.jpg','default'),
			(4,'news','<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\r\n<head>\r\r\n<meta name=\"google-site-verification\" content=\"jlPUD5SVPm4gKxr1AvDNT7e1khf8uzP5D15mRvasIpI\" />\r\r\n<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\r\r\n<title>{\$page_title}</title>\r\r\n<meta name=\"keywords\" content=\"{\$meta_keywords}\" /> \r\r\n<meta name=\"description\" content=\"{\$meta_description}\" /> \r\r\n<link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\r\r\n<link href=\"content.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\r\r\n</head>\r\r\n\r\r\n\r\r\n\r\r\n<body>\r\r\n<div id=\"wrapper\">\r\r\n{\$static_menu}\r\r\n<!-- start page -->\r\r\n<div id=\"page\">\r\r\n	<!-- start content -->\r\r\n	<div id=\"content\">\r\r\n\r\r\n	<div id=\"logo\">{\$content:topimage}\r\r\n    <div id=\"logo-title\">\r\r\n   <h1>{\$header:slogan}</h1>\r\r\n    </div>\r\r\n    	</div>\r\r\n		<div class=\"post\">\r\r\n			<h2 class=\"title\">{\$header:3}</h2> \r\r\n			<div class=\"entry\">\r\r\n				{\$content:2}\r\r\n		  </div>\r\r\n\r\r\n		</div>\r\r\n		\r\r\n	</div>\r\r\n	<!-- end content -->\r\r\n	<!-- start sidebars -->\r\r\n	<div id=\"sidebar1\" class=\"sidebar\">\r\r\n	{\$main_menu}	\r\r\n<script language=\"javascript\">setPage();</script>\r\r\n	</div>\r\r\n	<div id=\"sidebar2\" class=\"sidebar\">\r\r\n		\r\r\n				<h2>{\$header:2}</h2>\r\r\n\r\r\n{\$content:1}\r\r\n\r\r\n<h2>{\$header:4}</h2>\r\r\n\r\r\n{\$content:3}\r\r\n\r\r\n\r\r\n\r\r\n			\r\r\n	</div>\r\r\n	<!-- end sidebars -->\r\r\n	<div style=\"clear: both;\">&nbsp;</div>\r\r\n<!-- end page -->\r\r\n</div>\r\r\n<div id=\"footer\">\r\r\n	{\$static:footer}\r\r\n</div>\r\r\n</div>\r\r\n</body>\r\r\n</html>','news.jpg','default');"
	,"CREATE TABLE `lexem` (
          `id` int(10) unsigned NOT NULL auto_increment,
          `original_value` text NOT NULL,
          PRIMARY KEY  (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;",

		"CREATE TABLE `lexem_has_language` (
                      `lexem_id` int(10) unsigned NOT NULL,
                      `language_id` int(10) unsigned NOT NULL,
                      `value` text
                    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
		
		"CREATE TABLE `translate_languages` (                    
                       `id` int(10) unsigned NOT NULL auto_increment,        
                       `language` varchar(60) NOT NULL,                      
                       PRIMARY KEY  (`id`)                                   
                     ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;",
		"insert  into `translate_languages`(`id`,`language`)
		values (1,'German'),(2,'French');",

	"CREATE PROCEDURE `replaceDeeplinkUrl`(IN oldUrl VARCHAR(255), IN newUrl VARCHAR(255))
	BEGIN
		DECLARE minId INT(10);
		DECLARE maxId INT(10);
		SELECT MIN(`deeplink`.`id`) INTO minId FROM `deeplink` WHERE `deeplink`.`url` = oldUrl;
		SELECT MAX(`deeplink`.`id`) INTO maxId FROM `deeplink` WHERE `deeplink`.`url` = oldUrl;
		UPDATE `deeplink` SET `deeplink`.`url` = newUrl WHERE `deeplink`.`id` BETWEEN minId AND maxId;
	END;"
	);
}

try {
	$install = new Install();
	$step = (isset($_POST['step'])?intval($_POST['step']):0);

	switch ($step) {
		case '0':
			$install->Welcome();
			break;
		case '1':
			$install->Step1();
			break;
		case '2':
			$install->Step2();
			break;
		case '3':
			$install->Step3();
			break;
		case '4':
			$install->ThankYou();
			break;
		default:
			$install->Welcome();
			break;
	}
}
catch (Exception $e) {
	echo $e->getMessage();
}

?>